<?php

namespace app\models\factory;

use app\Auth;
use app\models\warehouse\OrderCartInfo;
use app\Request;
use think\facade\Cache;
use think\facade\Db;
use think\Model;
use lc\helpers\Helper;

class Order extends Model
{

    protected $table = 'xd_store_order';


    /**
     * 记录日志
     * @param $waterId
     * @param $admin
     * @param $status
     * @return int
     */
    public function addLog($waterId,$admin,$status,$type){

        if($type == 1){
            //订单日志
            $insert = [
                'order_id'=>$waterId,
                'staff_id'=>$admin->id,
                'store_id'=>$admin->store_id,
                'status'=>$status,
                'created_time'=>date('Y-m-d H:i:s')
            ];
        }else{
            //衣物日志
            $insert = [
                'water_id'=>$waterId,
                'staff_id'=>$admin->id,
                'store_id'=>$admin->store_id,
                'status'=>$status,
                'created_time'=>date('Y-m-d H:i:s')
            ];
        }

        Db::table('xd_store_order_log')->insert($insert);

        return 1;
    }

    public function OrderCartInfo()
    {
        //点赞记录
        return $this->hasMany(OrderCartInfo::class, 'oid', 'id');
    }

    /**
     * 雪花算法生成订单id
     * @param string $prefix
     * @return string
     * @throws \Exception
     */
    public function getNewOrderId(string $prefix = 'wx')
    {

        $snowflake = new \Godruoyi\Snowflake\Snowflake();
        $is_callable = function ($currentTime) {
            $redis = Cache::store('redis');
            $swooleSequenceResolver = new \Godruoyi\Snowflake\RedisSequenceResolver($redis->handler());
            return $swooleSequenceResolver->sequence($currentTime);
        };
        //32位
        if (PHP_INT_SIZE == 4) {
            $id = abs($snowflake->setSequenceResolver($is_callable)->id());
        } else {
            $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->setSequenceResolver($is_callable)->id();
        }
        return $prefix . $id;
    }


    /**
     * 获取购物车商品详情
     * @return void
     */
    public function getgoodDeilt($id)
    {


        $data = Db::table('xd_store_product')->where('id', $id)->where('is_show', '1')->find();

        $data['resurt'] = Db::table('xd_store_product_attr_result')->where('product_id', $id)->find();
        $data['value'] = Db::table('xd_store_product_attr_value')->where('product_id', $id)->find();
        $data['description'] = Db::table('xd_store_product_description')->where('product_id', $id)->find();

        return $data;
    }


    public function getCartData($cartId)
    {

        $data = Db::table('xd_store_cart')
            ->alias('c')
            ->field('c.cart_num,p.price')
            ->whereIn('c.id', $cartId)
            ->leftjoin(['xd_store_product' => 'p'], 'p.id=c.product_id')
            ->select();

        if (!empty($data)) {

            $price = 0;
            $num = 0;
            foreach ($data as $k => $v) {
                $price = $price + $v['cart_num'] * $v['price'];
                $num = $num + $v['cart_num'];
            }
            $res = [
                'price' => $price,
                'num' => $num
            ];
        } else {
            $res = [
                'price' => 0,
                'num' => 0
            ];
        }
        return $res;
    }


    /**
     * 出厂
     */

    public function leaveFactory($oId, $admin)
    {

        //查询订单和订单下的衣物信息
        $orderData = Db::table('xd_store_order')->where('id', $oId)->find();
        $goodsInfo = Db::table('xd_store_order_goodsInfo')->where('oid', $oId)->select()->toArray();

        $no = '0';
        foreach ($goodsInfo as $k => $v) {
            if ($v['fidjson'] != '') {
                $fid = json_decode($v['fidjson'], true);
                $no = $no + count($fid);
            }
        }

        $reamk = "格架【" . $goodsInfo[0]['shelf_no'] . '】共:' . count($goodsInfo) . ' 附件:' . $no;

        //给jd下单
//        $baseUri = "https://api.jdl.com";
        $baseUri = "https://uat-api.jdl.com";
        $appKey = "1eb37f16f53b4982ab5f87c852cef46e";
        $appSecret = "23b2f268e08140a1837de4df94e2e77b";
//        $accessToken = "b3b2cc3e002f4c3d83311c8eb54efae4";
        $accessToken = "f0da813236d5424d9d2b1af2bdcc2a91";

        $domain = "ECAP";
        $path = "/ecap/v1/orders/create";
        $method = "post";
        $algorithm = "md5-salt";


        $addressData = Db::table('xd_system_store')->where('id', $admin->store_id)->find();

        if (empty($addressData)) {

            return [
                'code' => 1000,
                'msg' => '未找到地址,请联系管理员'
            ];
        }

        $shou = [
            'name' => '星涤洗护工厂',
            'mobile' => $addressData['phone'],
            'fullAddress' => $addressData['detailed_address'],
        ];
        $jdkey = '028K2835294';


        $body = '[
                    {
                     "orderId": "' . $goodsInfo[0]['shelf_no'] . '-' . $orderData['order_id'] . '",
                     "senderContact": {
                      "name": "' . $shou['name'] . '",
                      "mobile": "' . $shou['mobile'] . '",
                      "fullAddress": "' . $shou['fullAddress'] . '"
                     },
                     "receiverContact": {
                      "name": "' . $orderData['real_name'] . '",
                      "mobile": "' . $orderData['user_phone'] . '",
                      "fullAddress": "' . $orderData['user_address'] . '"
                     },
                     "orderOrigin": "1",
                     "customerCode": "' . $jdkey . '",
                     "productsReq": {
                      "productCode": "ed-m-0001"
                     },
                     "settleType": "3",
                     "cargoes": [
                      {
                      "name": "衣服",
                      "quantity": "1",
                      "weight": "1",
                      "volume": "1"
                      }
                     ],
                     "remark":"' . $reamk . '"
                    }
                  ]';

        $data = json_encode(json_decode($body,true));
        $timestamp = date("Y-m-d H:i:s");
        $content = implode("", array(
            $appSecret,
            "access_token", $accessToken,
            "app_key", $appKey,
            "method", $path,
            "param_json", $data,
            "timestamp", $timestamp,
            "v", "2.0",
            $appSecret
        ));

        $sign = md5($content);

        $query = http_build_query(array(
            "LOP-DN" => $domain,
            "app_key" => $appKey,
            "access_token" => $accessToken,
            "timestamp" => $timestamp,
            "v" => "2.0",
            "sign" => $sign,
            "algorithm" => $algorithm
        ));

        $uri = $baseUri . $path . "?" . $query;

        $data12  = Helper::http_request($uri,$data);

        $rda  = json_decode($data12,true);

        Db::table('xd_store_api_log')->insert([
            'query'=>$uri,
            'res'=>$data12,
            'data'=>$body,
            'add_time'=>date('Y-m-d H:i:s')
        ]);

        if($rda['code'] =='0'){
            // $waybillCode = $rda['data']['waybillCode'];
            if(isset($rda['data']['waybillCode'])){
                $waybillCode = $rda['data']['waybillCode'];
                $status = '1';
            }else{
                $waybillCode = '';
                $status = '0';
            }
        }else{
            return [
                'code' => 1000,
                'msg' => $rda['msg']
            ];
        }

        $kd = array(
            'status'=>'2',
            'delivery_name'=>'京东快递',
            'delivery_code'=>'JD',
            'delivery_type'=>'1',
            'delivery_id'=>$waybillCode,
            'delivery_time'=>date('Y-m-d H:i:s'),
            'order_status'=>7
        );

        Db::table('xd_store_order')->where('id', $oId)->update($kd);
        Db::table('xd_store_order_goodsInfo')->where('oid', $oId)->update([
            'status'=>7
        ]);

        $jddata = array(
            'oid'=>$oId,
            'uid'=>$orderData['uid'],
            'jdcode'=>$waybillCode,
            'username'=>$orderData['real_name'],
            'phone'=>$orderData['user_phone'],
            'address'=>$orderData['user_address'],
            'reamk'=>$reamk,
            'store_id'=>$orderData['store_id'],
            'pylons_no'=>$goodsInfo[0]['shelf_no'],
            'status'=>$status,
            'factorytime'=>$timestamp
        );

        /**
         * 新增出厂记录
         */

        Db::table('xd_store_order_factoryIssue')->insert($jddata);

        return ['code'=>0,'data'=>$waybillCode];
    }





}
